#############################################################################
#
# Just Another Package Builder http://code.google.com/p/japb
# (c)2012 Alexander Galanin
#
# Archive file target support
#
# Tar archives are supported by Tcl library, all others — via external
# executables.
#
# $Id$
#
#############################################################################

package require Tcl 8.5
package require japb
package require japb::filenode

package provide japb::archive 1.0

namespace eval japb {

namespace export archive

namespace eval archive {

namespace import ::japb::dir
namespace import ::japb::filenode

# Prepare directory for archiving, copy files into it and execute archiving
# script. All actions are performed inside archiving directory and path is
# restored after successful completion or on error. Destination file node is
# passed into archiving script via variable 'out', file list --- via variable
# 'files'.
# @params archiveName name for archive file
# @param archiveScript archiving commands
# @param args file nodes to archive
# @return destination archive node
proc doArchiving {archiveName archiveScript args} {
    set out [filenode mkfile $archiveName]
    set dirnode [dir archive-$archiveName {*}$args]

    set pwd [pwd]
    cd [filenode path $dirnode]
    set files [glob -nocomplain *]
    if {[catch $archiveScript err opts]} {
        # restore dir on error
        cd $pwd
        return -options $opts $err
    }
    cd $pwd

    return $out
}

# Create tar archive (by using Tcl library)
proc tar {fname args} {
    doArchiving $fname.tar {
        ::tar::create [filenode path $out] {*}$files
    } {*}$args
}

# Create zip archive (using external command)
proc zip {fname args} {
    doArchiving $fname.zip {
        exec zip -r [filenode path $out] {*}$files
    } {*}$args
}

# Check that corresponding archive type is supported
proc isSupported {type} {
    variable tarSupported

    switch $type {
        tar {
            set tarSupported [expr {![catch {package require tar 0.6}]}]
            return $tarSupported
        }
        zip {
            return [expr {[auto_execok zip] ne ""}]
        }
        default {
            return false
        }
    }
}

namespace export \
    tar \
    zip \
    isSupported
namespace ensemble create
}
}
